const express = require('express')
const { body, validationResult } = require('express-validator')
const { query: dbQuery, transaction } = require('../config/database')
const { authenticateToken } = require('../middleware/auth')
const { v4: uuidv4 } = require('uuid')
const moment = require('moment')

const router = express.Router()

// 充值套餐配置
const rechargePackages = [
  {
    id: 'pkg_1',
    amount: 100,
    price: 10,
    bonus: 0,
    description: '新手套餐',
    isPopular: false
  },
  {
    id: 'pkg_2',
    amount: 300,
    price: 30,
    bonus: 20,
    description: '基础套餐',
    isPopular: false
  },
  {
    id: 'pkg_3',
    amount: 500,
    price: 50,
    bonus: 50,
    description: '推荐套餐',
    isPopular: true
  },
  {
    id: 'pkg_4',
    amount: 1000,
    price: 100,
    bonus: 150,
    description: '超值套餐',
    isPopular: false
  },
  {
    id: 'pkg_5',
    amount: 2000,
    price: 200,
    bonus: 400,
    description: '豪华套餐',
    isPopular: false
  }
]

// VIP套餐配置
const vipPackages = [
  {
    type: 'monthly',
    name: '月度VIP',
    price: 15,
    duration: '1个月',
    features: ['VIP章节免费', '无广告阅读', '优先更新', '专属标识']
  },
  {
    type: 'yearly',
    name: '年度VIP',
    price: 128,
    duration: '12个月',
    features: ['VIP章节免费', '无广告阅读', '优先更新', '专属标识', '专属客服']
  }
]

/**
 * @swagger
 * /api/payment/packages:
 *   get:
 *     summary: 获取充值套餐
 *     tags: [支付]
 *     responses:
 *       200:
 *         description: 充值套餐列表
 */
router.get('/packages', (req, res) => {
  res.success(rechargePackages, '获取充值套餐成功')
})

/**
 * @swagger
 * /api/payment/vip-packages:
 *   get:
 *     summary: 获取VIP套餐
 *     tags: [支付]
 *     responses:
 *       200:
 *         description: VIP套餐列表
 */
router.get('/vip-packages', (req, res) => {
  res.success(vipPackages, '获取VIP套餐成功')
})

/**
 * @swagger
 * /api/payment/wallet:
 *   get:
 *     summary: 获取钱包信息
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 钱包信息
 */
router.get('/wallet', authenticateToken, async (req, res, next) => {
  try {
    // 获取用户信息
    const userRows = await dbQuery(
      'SELECT coins, is_vip, vip_expire_date FROM users WHERE id = ?',
      [req.user.id]
    )

    if (userRows.length === 0) {
      return res.error('用户不存在', 'USER_NOT_FOUND')
    }

    const user = userRows[0]

    // 获取充值统计
    const rechargeStats = await dbQuery(
      `SELECT 
        COALESCE(SUM(CASE WHEN type = 'recharge' THEN amount ELSE 0 END), 0) as totalRecharge,
        COALESCE(SUM(CASE WHEN type = 'consumption' THEN amount ELSE 0 END), 0) as totalConsumption
       FROM payment_orders 
       WHERE user_id = ? AND status = 'paid'`,
      [req.user.id]
    )

    const stats = rechargeStats[0] || { totalRecharge: 0, totalConsumption: 0 }

    const walletInfo = {
      balance: user.coins || 0,
      totalRecharge: stats.totalRecharge || 0,
      totalConsumption: stats.totalConsumption || 0,
      vipInfo: {
        isVip: user.is_vip || false,
        vipType: user.is_vip
          ? user.vip_expire_date &&
            moment(user.vip_expire_date).diff(moment(), 'months') >= 11
            ? 'yearly'
            : 'monthly'
          : undefined,
        expiresAt: user.vip_expire_date || undefined
      }
    }

    res.success(walletInfo, '获取钱包信息成功')
  } catch (error) {
    next(error)
  }
})

/**
 * @swagger
 * /api/payment/recharge:
 *   post:
 *     summary: 创建充值订单
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - packageId
 *               - paymentMethod
 *             properties:
 *               packageId:
 *                 type: string
 *                 description: 套餐ID
 *               paymentMethod:
 *                 type: string
 *                 enum: [alipay, wechat, mock]
 *                 description: 支付方式
 *     responses:
 *       200:
 *         description: 订单创建成功
 */
router.post(
  '/recharge',
  [
    authenticateToken,
    body('packageId').notEmpty().withMessage('套餐ID不能为空'),
    body('paymentMethod')
      .isIn(['alipay', 'wechat', 'mock'])
      .withMessage('支付方式无效')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const { packageId, paymentMethod } = req.body

      // 查找套餐
      const selectedPackage = rechargePackages.find(pkg => pkg.id === packageId)
      if (!selectedPackage) {
        return res.error('套餐不存在', 'PACKAGE_NOT_FOUND')
      }

      const orderNo = `RECHARGE_${Date.now()}_${uuidv4().slice(0, 8)}`
      const totalCoins = selectedPackage.amount + selectedPackage.bonus

      // 创建订单
      await dbQuery(
        `INSERT INTO payment_orders (user_id, order_no, type, amount, payment_method, metadata)
         VALUES (?, ?, 'coins', ?, ?, ?)`,
        [
          req.user.id,
          orderNo,
          selectedPackage.price,
          paymentMethod,
          JSON.stringify({
            packageId: selectedPackage.id,
            coinsToAdd: totalCoins,
            baseAmount: selectedPackage.amount,
            bonusAmount: selectedPackage.bonus
          })
        ]
      )

      // 模拟支付成功
      if (paymentMethod === 'mock') {
        await processRechargePaymentSuccess(orderNo, totalCoins, req.user.id)

        res.success(
          {
            orderNo,
            status: 'paid',
            amount: selectedPackage.price,
            coinsAdded: totalCoins,
            message: '模拟支付成功，书币已到账'
          },
          '充值成功'
        )
      } else {
        res.success(
          {
            orderNo,
            amount: selectedPackage.price,
            paymentMethod,
            paymentUrl: `https://mock-payment.com/pay?order=${orderNo}&amount=${selectedPackage.price}`,
            message: '请完成支付'
          },
          '订单创建成功'
        )
      }
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/payment/vip:
 *   post:
 *     summary: 购买VIP
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - type
 *               - paymentMethod
 *             properties:
 *               type:
 *                 type: string
 *                 enum: [monthly, yearly]
 *                 description: VIP类型
 *               paymentMethod:
 *                 type: string
 *                 enum: [alipay, wechat, mock]
 *                 description: 支付方式
 *     responses:
 *       200:
 *         description: 订单创建成功
 */
router.post(
  '/vip',
  [
    authenticateToken,
    body('type').isIn(['monthly', 'yearly']).withMessage('VIP类型无效'),
    body('paymentMethod')
      .isIn(['alipay', 'wechat', 'mock'])
      .withMessage('支付方式无效')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const { type, paymentMethod } = req.body

      // 检查用户当前VIP状态
      const userResult = await dbQuery(
        'SELECT vip_type, vip_expire_date FROM users WHERE id = ?',
        [req.user.id]
      )

      if (userResult.length === 0) {
        return res.error('用户不存在', 'USER_NOT_FOUND')
      }

      const user = userResult[0]
      const now = new Date()
      const isVipActive =
        user.vip_expire_date && new Date(user.vip_expire_date) > now

      // VIP开通逻辑检查
      if (isVipActive) {
        if (user.vip_type === 'yearly') {
          return res.error(
            '您已是年度VIP用户，无需重复开通',
            'VIP_ALREADY_ACTIVE'
          )
        }
        if (user.vip_type === 'monthly' && type === 'monthly') {
          return res.error(
            '您已是月度VIP用户，请选择升级到年度VIP',
            'VIP_ALREADY_ACTIVE'
          )
        }
        // 如果是月度VIP想升级到年度VIP，允许继续
      }

      // VIP价格配置
      const vipPrices = {
        monthly: 15.0,
        yearly: 128.0
      }

      const amount = vipPrices[type]
      const orderNo = `VIP_${Date.now()}_${uuidv4().slice(0, 8)}`

      // 创建订单
      await dbQuery(
        `INSERT INTO payment_orders (user_id, order_no, type, amount, payment_method, metadata)
         VALUES (?, ?, 'vip', ?, ?, ?)`,
        [
          req.user.id,
          orderNo,
          amount,
          paymentMethod,
          JSON.stringify({ vipType: type })
        ]
      )

      // 模拟支付成功（实际项目中需要对接真实支付接口）
      if (paymentMethod === 'mock') {
        // 直接处理支付成功
        await processVipPaymentSuccess(orderNo, type, req.user.id)

        res.success(
          {
            orderNo,
            status: 'paid',
            message: '模拟支付成功，VIP已开通'
          },
          'VIP购买成功'
        )
      } else {
        // 返回支付信息（实际项目中返回支付URL或参数）
        res.success(
          {
            orderNo,
            amount,
            paymentMethod,
            paymentUrl: `https://mock-payment.com/pay?order=${orderNo}&amount=${amount}`,
            message: '请完成支付'
          },
          '订单创建成功'
        )
      }
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/payment/order/{orderNo}:
 *   get:
 *     summary: 查询订单状态
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: orderNo
 *         required: true
 *         schema:
 *           type: string
 *         description: 订单号
 *     responses:
 *       200:
 *         description: 订单信息
 */
router.get('/order/:orderNo', authenticateToken, async (req, res, next) => {
  try {
    const { orderNo } = req.params

    const orderRows = await dbQuery(
      'SELECT * FROM payment_orders WHERE order_no = ? AND user_id = ?',
      [orderNo, req.user.id]
    )

    if (orderRows.length === 0) {
      return res.error('订单不存在', 'ORDER_NOT_FOUND')
    }

    const order = orderRows[0]
    res.success(
      {
        orderNo: order.order_no,
        amount: order.amount,
        status: order.status,
        paymentMethod: order.payment_method,
        createdAt: order.created_at
      },
      '获取订单信息成功'
    )
  } catch (error) {
    next(error)
  }
})

/**
 * @swagger
 * /api/payment/records:
 *   get:
 *     summary: 获取交易记录
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: type
 *         schema:
 *           type: string
 *           enum: [recharge, consumption, vip]
 *         description: 交易类型
 *     responses:
 *       200:
 *         description: 交易记录列表
 */
router.get('/records', authenticateToken, async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 10
    const type = req.query.type
    const offset = (page - 1) * limit

    let whereClause = 'WHERE user_id = ?'
    let countParams = [req.user.id]
    let recordParams = [req.user.id]

    if (type) {
      whereClause += ' AND type = ?'
      countParams.push(type)
      recordParams.push(type)
    }

    // 获取总数
    const countRows = await dbQuery(
      `SELECT COUNT(*) as total FROM payment_orders ${whereClause}`,
      countParams
    )
    const total = countRows[0].total

    // 获取记录
    recordParams.push(limit, offset)
    const records = await dbQuery(
      `SELECT 
        id, order_no, type, amount, status, payment_method, 
        metadata, created_at, updated_at
       FROM payment_orders 
       ${whereClause}
       ORDER BY created_at DESC 
       LIMIT ? OFFSET ?`,
      recordParams
    )

    // 格式化记录
    const formattedRecords = records.map(record => {
      let description = ''
      const metadata = record.metadata ? JSON.parse(record.metadata) : {}

      switch (record.type) {
        case 'recharge':
          description = `充值 ${metadata.coinsToAdd || 0} 书币`
          break
        case 'vip':
          description = `购买${
            metadata.vipType === 'yearly' ? '年度' : '月度'
          }VIP`
          break
        case 'consumption':
          description = metadata.description || '消费'
          break
        default:
          description = record.type
      }

      return {
        id: record.id,
        type: record.type,
        amount: record.amount,
        description,
        createdAt: record.created_at,
        status: record.status
      }
    })

    res.success(
      {
        records: formattedRecords,
        total,
        page,
        limit
      },
      '获取交易记录成功'
    )
  } catch (error) {
    next(error)
  }
})

/**
 * @swagger
 * /api/payment/mock-success/{orderNo}:
 *   post:
 *     summary: 模拟支付成功
 *     tags: [支付]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: orderNo
 *         required: true
 *         schema:
 *           type: string
 *         description: 订单号
 *     responses:
 *       200:
 *         description: 支付成功
 */
router.post(
  '/mock-success/:orderNo',
  authenticateToken,
  async (req, res, next) => {
    try {
      const { orderNo } = req.params

      const orderRows = await dbQuery(
        'SELECT * FROM payment_orders WHERE order_no = ? AND user_id = ?',
        [orderNo, req.user.id]
      )

      if (orderRows.length === 0) {
        return res.error('订单不存在', 'ORDER_NOT_FOUND')
      }

      const order = orderRows[0]

      if (order.status === 'paid') {
        return res.error('订单已支付', 'ORDER_ALREADY_PAID')
      }

      const metadata = order.metadata ? JSON.parse(order.metadata) : {}

      // 根据订单类型处理支付成功
      switch (order.type) {
        case 'vip':
          await processVipPaymentSuccess(orderNo, metadata.vipType, req.user.id)
          break
        case 'recharge':
          await processRechargePaymentSuccess(
            orderNo,
            metadata.coinsToAdd,
            req.user.id
          )
          break
        default:
          return res.error('不支持的订单类型', 'UNSUPPORTED_ORDER_TYPE')
      }

      res.success({ orderNo, status: 'paid' }, '支付成功')
    } catch (error) {
      next(error)
    }
  }
)

// 处理VIP支付成功
async function processVipPaymentSuccess (orderNo, vipType, userId) {
  await transaction(async connection => {
    // 更新订单状态
    await connection.execute(
      'UPDATE payment_orders SET status = "paid", updated_at = CURRENT_TIMESTAMP WHERE order_no = ?',
      [orderNo]
    )

    // 计算VIP到期时间
    const now = moment()
    let vipExpiresAt

    if (vipType === 'monthly') {
      vipExpiresAt = now.add(1, 'month').format('YYYY-MM-DD HH:mm:ss')
    } else if (vipType === 'yearly') {
      vipExpiresAt = now.add(1, 'year').format('YYYY-MM-DD HH:mm:ss')
    }

    // 更新用户VIP状态
    await connection.execute(
      'UPDATE users SET is_vip = true, vip_type = ?, vip_expire_date = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [vipType, vipExpiresAt, userId]
    )
  })
}

// 处理充值支付成功
async function processRechargePaymentSuccess (orderNo, coinsToAdd, userId) {
  await transaction(async connection => {
    // 更新订单状态
    await connection.execute(
      'UPDATE payment_orders SET status = "paid", updated_at = CURRENT_TIMESTAMP WHERE order_no = ?',
      [orderNo]
    )

    // 增加用户书币
    await connection.execute(
      'UPDATE users SET coins = coins + ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [coinsToAdd, userId]
    )
  })
}

module.exports = router
